package com.reggie.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reggie.common.R;
import com.reggie.entity.Category;
import com.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 菜品及套餐分类(Category)表控制层
 *
 * @author makejava
 * @since 2022-09-01 11:49:52
 */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    /**
     * 服务对象
     */
    @Resource
    private CategoryService categoryService;

    /**
     * 新增分类
     *
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        log.info("当前线程：{}", Thread.currentThread().getId());
        log.info("新增分类：{}", category);
        categoryService.save(category);
        return R.success("新增分类成功");
    }

    /**
     * 分页查询
     *
     * @param currPage
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page<Category>> page(@RequestParam("page") int currPage, @RequestParam("pageSize") int pageSize) {
        log.info("当前线程：{}", Thread.currentThread().getId());
        Page<Category> pageinfo = new Page<>(currPage, pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        // 添加排序条件
        queryWrapper.orderByAsc(Category::getSort);
        categoryService.page(pageinfo, queryWrapper);
        return R.success(pageinfo);
    }

    @DeleteMapping("/{id}")
    public R<String> delete(@PathVariable("id") Long categoryId) {
        log.info("当前线程：{}", Thread.currentThread().getId());
        // categoryService.removeById(categoryId);
        categoryService.remove(categoryId);
        return R.success("删除成功");
    }

    /**
     * 根据id修改分类信息
     *
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        log.info("修改分类：{}", category);
        log.info("当前线程：{}", Thread.currentThread().getId());
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    @GetMapping("/list")
    public R<List<Category>> list(Category category) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BeanUtil.isNotEmpty(category), Category::getType, category.getType())
                .orderByAsc(Category::getSort)
                .orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }
}

